from django import forms
from django.core.exceptions import ValidationError

from web import models
from web.forms.bootstrap import BootStripForm
from web.forms.widgets import ColorRadioSelect


class ProjectModelForm(BootStripForm, forms.ModelForm):
    bootstrap_class_exclude=['color']
    # desc=forms.CharField(widget=forms.Textarea)
    class Meta:
        model = models.Project
        fields = ['name', 'color', 'desc']
        widgets = {
            'desc': forms.Textarea,
            'color':ColorRadioSelect(attrs={'class':'color-radio'}),
        }


    def __init__(self, request, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.request = request

    def clean_name(self):
        """项目校验"""
        name = self.cleaned_data['name']
        user = self.request.tracer.user
        # 1.项目名不能重复（当前用户）
        exists = models.Project.objects.filter(name=name, creator=user).exists()
        if exists:
            raise ValidationError('项目名已存在')
        # 2.当前用户是否还有额度进行创建项目
        # 2.1项目额度
        # self.request.tracer.price_policy.project_num
        # 2.2当前已经创建的项目
        count = models.Project.objects.filter(creator=user).count()
        if count >= self.request.tracer.price_policy.project_num:
            raise ValidationError('项目个数超限，请购买套餐')
        return name

        # 3.当前用户的
